package com.example.auth.datasource;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.activation.DataContentHandler;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.example.auth.mapper")
public class MultiDataSourceConfig {
    private Logger logger  = LoggerFactory.getLogger(MultiDataSourceConfig.class);
    @Autowired
    private DataSource dataSourceAuth;
    @Autowired
    private DataSource dataSourceConsumer;
    @Autowired
    private DataSource dataSourceMq;
    @Autowired
    private DataSource dataSourceGateway;
    @Autowired
    private DataSource dataSourceSystem;
    @Autowired
    @Qualifier("dynamicDataSource")
    private DataSource dynamicDataSource;
    @Autowired
    private StringEncryptor stringEncryptor;
    @Bean(name = "dataSourceAuth")
    @ConfigurationProperties(prefix = "spring.datasource.auth")
    public DataSource dataSourceAuth() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSourceConsumer")
    @ConfigurationProperties(prefix = "spring.datasource.consumer")
    public DataSource dataSourceConsumer() {

        return DataSourceBuilder.create().build();
    }
    @Bean(name = "dataSourceMq")
    @ConfigurationProperties(prefix = "spring.datasource.mq")
    public DataSource dataSourceMq() {

        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSourceGateway")
    @ConfigurationProperties(prefix = "spring.datasource.gateway")
    public DataSource dataSourceGateway() {

        return DataSourceBuilder.create().build();
    }
    @Bean(name = "dataSourceSystem")
    @ConfigurationProperties(prefix = "spring.datasource.system")
    public DataSource dataSourceSystem() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        //注册乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword("encryptionkey"); // 加密密钥
        config.setAlgorithm("PBEWithHmacSHA512AndAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }
    @PostConstruct
    public void init(){
      /* String  enStr  = stringEncryptor.encrypt("Root@123");
       String  deSTr  = stringEncryptor.decrypt("N8VBWG5nOHvy5efX3/mlPAmdBykE7iDZFl362LyeaPRXMbLT0PzEIlB/KDXrNYz6");
        System.out.println("enStr==="+enStr);
        System.out.println("deSTr==="+deSTr);*/
    }
    /**
     * 不加
     * @param interceptor
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory (MybatisPlusInterceptor interceptor) throws Exception {
        MybatisSqlSessionFactoryBean ssfb = new MybatisSqlSessionFactoryBean();
        ssfb.setDataSource(dynamicDataSource); // 使用 DynamicDataSource
        ssfb.setPlugins(interceptor);
        ssfb.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:/mapper/*Mapper.xml"));
        return ssfb.getObject();
    }

    @Bean
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 假设你有多个数据源，需要在这里将它们添加到 targetDataSources 中
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("dataSourceSystem", dataSourceSystem);
        targetDataSources.put("dataSourceAuth", dataSourceAuth);
        targetDataSources.put("dataSourceConsumer", dataSourceConsumer);
        targetDataSources.put("dataSourceMq", dataSourceMq);
        targetDataSources.put("dataSourceGateway",dataSourceGateway);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(dataSourceSystem);// 设置默认数据源
        return dynamicDataSource;
    }

}
